package com.feng.security.jarsigner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.CodeSigner;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;

import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.xmlpull.v1.XmlPullParserException;

import com.lenovo.lmm.appman.AppProperties;
import com.lenovo.lmm.appman.logic.delegate.AppDelegate;
import com.lenovo.lmm.appman.logic.model.AmsApp;
import com.lenovo.lmm.appman.logic.model.AmsAppSysInfo;
import com.lenovo.lmm.appman.logic.model.AmsAppimg;
import com.lenovo.lmm.appman.logic.model.AmsAppsubmitImage;
import com.lenovo.lmm.appman.logic.model.AmsAppsubmitInfo;
import com.lenovo.lmm.appman.logic.model.AmsAppsubmitManifest;
import com.lenovo.lmm.devcommunity.web.action.appmanage.mediautil.LLJTranUtil;
import com.lenovo.lmm.devcommunity.web.common.ApkUtil;
import com.lenovo.lmm.devcommunity.web.factory.LanguageResourceFactory;
import com.lenovo.lmm.devcommunity.web.form.appmanage.AmsAppFrom;
import com.lenovo.lmm.framework.base.exception.ErrorCode;
import com.lenovo.lmm.framework.base.exception.LmmException;
import com.lenovo.lps.appstore.security.AesCrypto;
import com.lenovo.security.tools.CheckSigner;


public class AppLogicBean  {
		
	/**
	 * 如果返回-1 名称为空 -2 简介为空 -3 价格为空  -4 类型为空 -5 作者为空 -6 包类型为空
	 * -7 包名为空 -8 版本号为空 -9 版本号出现非数字 -10  版本号第一数字不能为0  -11 版本名为空
	 * -12 支持设配类型为空 -13 支持版本为空 -14 pushid为空 -15 没有一第图片 -20 没有上传包 -21 快照小于3张 -22 宣传图为空 -23 图标为空
	 * 1 全部正确
	 * -30 正式版本jad文件为空 -31 试用版本jad文件为空 -32 正式版本lca包为空 -33 试用版本lca包为空
	 * @param amsAppsubmitInfo
	 * @return
	 */
	public int checkData(AmsAppsubmitInfo amsAppsubmitInfo){
		
		if(null==amsAppsubmitInfo.getAppName()||"".equals(amsAppsubmitInfo.getAppName().trim())){
			return -1;
		}
		if(null==amsAppsubmitInfo.getSIntro()||"".equals(amsAppsubmitInfo.getSIntro().trim())){
			return -2;
		}

		if(null==amsAppsubmitInfo.getPrice()){
			return -3;
		}else{
			
		}	
		if(null==amsAppsubmitInfo.getAppTypeId()||amsAppsubmitInfo.getAppTypeId()==0){
			return -4;
		}		
		if(null==amsAppsubmitInfo.getAuthor()||"".equals(amsAppsubmitInfo.getAuthor().trim())){
			return -5;
		}
		if(null==amsAppsubmitInfo.getPackageTypeId()){
			return -6;
		}

		
		if(null==amsAppsubmitInfo.getDeviceSupport()||"".equals(amsAppsubmitInfo.getDeviceSupport().trim())){
			return -12;
		}
		if(null==amsAppsubmitInfo.getSupportMinVersion()||"".equals(amsAppsubmitInfo.getSupportMinVersion().trim())){
			return -13;
		}
		if(null!=amsAppsubmitInfo.getPushEnable()&&amsAppsubmitInfo.getPushEnable()==1){
			if(null==amsAppsubmitInfo.getPushId()||"".equals(amsAppsubmitInfo.getPushId().trim())){
				return-14;
			}
		}

		//图片部分
		Set<AmsAppsubmitImage> set =amsAppsubmitInfo.getAmsAppsubmitImages();
		if(set==null){
			return -15;
		}
		int coutImg0=0;
		int coutImg1=0;
		int coutImg2=0;
		int coutImg3=0;
		int coutImg4=0;
		int coutImg5=0;
		int coutImg6=0;
		int coutImg7=0;
		int coutImg8=0;
		int coutImg9=0;
		int coutImg10=0;
		
		for( AmsAppsubmitImage img:set){
			if(img.getImageType()==1){
				coutImg1++;
			}else if(img.getImageType()==2){
				coutImg2++;
			}else if(img.getImageType()==3){
				coutImg3++;
			}else if(img.getImageType()==4){
				coutImg4++;
			}else if(img.getImageType()==5){
				coutImg5++;
			}else if(img.getImageType()==0){
				coutImg0++;
			}else if(img.getImageType()==6){//正式lca
				coutImg6++;
			}else if(img.getImageType()==7){//试用包
				coutImg7++;
			}else if(img.getImageType()==8){//试用lca
				coutImg8++;
			}else if(img.getImageType()==9){//正式jad
				coutImg9++;
			}else if(img.getImageType()==10){//试用jad
				coutImg10++;
			}
		}
		if(coutImg0==0){
			return -20;
		}
		if(coutImg1<3){
			return -21;
		}
		if(coutImg2==0){
			return -22;
		}
		if(coutImg3==0){
			return -23;
		}
		
		if(null==amsAppsubmitInfo.getPackageName()||"".equals(amsAppsubmitInfo.getPackageName().trim())){
			return -7;
		}
		if(null==amsAppsubmitInfo.getAppVersioncode()||"".equals(amsAppsubmitInfo.getAppVersioncode().trim())){
			return -8;
		}else{
			//检是否数字
			String appPrice_str=amsAppsubmitInfo.getAppVersioncode().trim();
			String regex="^\\d+$";
			if(!appPrice_str.matches(regex)){
				return -9;
			}else{
				if(appPrice_str.charAt(0)=='0'){
					return -10;
				}
			}
		}
		if(null==amsAppsubmitInfo.getVersion()||"".equals(amsAppsubmitInfo.getVersion().trim())){
			return -11;
		}			
		
		//20100223 添加试用版本的相关检查
		if(amsAppsubmitInfo.getPackageTypeId()==1){
			if(coutImg9==0){
		    	 //20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
				//return -30;//必须正式的jad
			}
		}
		//试用包是jad包
		if(coutImg7>0&&amsAppsubmitInfo.getPackageTypeId()==1&&amsAppsubmitInfo.getIspay()==1){
			if(coutImg10==0){
				//20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
				//return -31; //
			}
		}
		//lca包检查
		if(coutImg6==0){
			return -32;//没有发现正式lca包
		}
		//lca包检查(存在试用包)
		if(coutImg8==0&&coutImg7>0&&amsAppsubmitInfo.getIspay()==1){
			return -33;//没有发现试用lca包
		}
		return 1;
	}
	/**
	 * 检查上传应用的全部信息。如果出错返回对应的 ActionError 信息,如果正确，则返回null
	 * 
	 * errorCode==1表示正确,返回null
	 * @param errorCode
	 * @return
	 */
	public ActionError getCheckSubmitErrorData(int errorCode){
		ActionError messages=null;
		/**
		 * 如果返回-1 名称为空 -2 简介为空 -3 价格为空  -4 类型为空 -5 作者为空 -6 包类型为空
		 * -7 包名为空 -8 版本号为空 -9 版本号出现非数字 -10  版本号第一数字不能为0  -11 版本名为空
		 * -12 支持的平台为空 -13 适配的系统版本号为空 -14 pushid为空 -15 没有一第图片 -20 没有上传包 -21 快照小于5张 -22 宣传图为空 -23 图标为空
		 * 1 全部正确
		 * -30 正式版本jad文件为空 -31 试用版本jad文件为空 -32 正式版本lca包为空 -33 试用版本lca包为空
		 * @param amsAppsubmitInfo
		 * @return
		 */		
		if(errorCode==-1){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0049"));
		}else if(errorCode==-2){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0075"));
		}else if(errorCode==-3){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0051"));
		}else if(errorCode==-4){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0077"));
		}else if(errorCode==-5){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0057"));
		}else if(errorCode==-6){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0079"));
		}else if(errorCode==-7){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0059"));
		}else if(errorCode==-8){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0060"));
		}else if(errorCode==-9){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0082"));
		}else if(errorCode==-10){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0083"));
		}else if(errorCode==-11){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0084"));
		}else if(errorCode==-12){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0063"));
		}else if(errorCode==-13){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0064"));
		}else if(errorCode==-14){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0087"));
		}else if(errorCode==-15){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0088"));
		}else if(errorCode==-20){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0089"));
		}else if(errorCode==-21){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0090"));
		}else if(errorCode==-22){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0091"));
		}else if(errorCode==-23){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0092"));
		}else if(errorCode==-30){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0093"));
		}else if(errorCode==-31){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0094"));
		}else if(errorCode==-32){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0095"));
		}else if(errorCode==-33){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0096"));
		}else if(errorCode!=1){
			messages=new ActionError(ERRORS_MESSAGE,LanguageResourceFactory.getString("CLASS0097"));
		}
		
		return messages;
	}
	public static List <AmsAppsubmitImage> getAmsAppsubmitImage(Set<AmsAppsubmitImage> amsAppsubmitImages, Long imgType){
		List list =new Vector();
		Set<AmsAppsubmitImage> set =amsAppsubmitImages;
		for( AmsAppsubmitImage img:set){
			if(img.getImageType().longValue()==imgType.longValue()){
				list.add(img);
			}
		}
		return list;
	}
	
	public List <AmsAppimg> getAmsAppimg(Set<AmsAppimg> amsAppimgs, Long imgType){
		List list =new Vector();
		Set<AmsAppimg> set =amsAppimgs;
		for( AmsAppimg img:set){
			if(Long.valueOf(img.getAppimgType()).longValue()==imgType.longValue()){
				list.add(img);
			}
		}
		return list;
	}
	/**
	 * 必须要的数据项
	 * request.getParameter("imgsIndexPath2")
	 * request.getParameter("imgsIndexPath3")
	 * @param amsAppsubmitInfo
	 * @param oldImgs
	 * @param request
	 * @param imgType
	 */
	public void fillImg(AmsAppsubmitInfo  amsAppsubmitInfo ,Set<AmsAppimg>oldImgs, Long imgType ){
		List<AmsAppimg> list=getAmsAppimg(oldImgs, imgType);
		if(list.size()>0){
			AmsAppimg amsAppimg=list.get(0);
			AmsAppsubmitImage amsAppsubmitImage=getAmsAppsubmitImage(amsAppimg);
			amsAppsubmitInfo.getAmsAppsubmitImages().add(amsAppsubmitImage);
		}
	}

	public void fillAmsAppsubmitImage(AmsAppsubmitInfo  amsAppsubmitInfo ,Set<AmsAppsubmitImage>amsAppsubmitImages, Long imgType ){
		List<AmsAppsubmitImage> list=this.getAmsAppsubmitImage(amsAppsubmitImages, imgType);
		for(AmsAppsubmitImage img: list ){
			amsAppsubmitInfo.getAmsAppsubmitImages().add(img);
		}
	}
	/**
	 * 升级检查数据项是否正确
	 * @param amsAppsubmitInfo
	 * @param amsApp
	 * @return 1 正确 -1:包名不同 -2 类型不同 -3 名称不同 -4 版本号低于原版本号 -5 价格不能更新
	 */
	public int checkUpgrade(AmsAppsubmitInfo  amsAppsubmitInfo, AmsApp amsApp ){
		if(!amsAppsubmitInfo.getPackageName().equals(amsApp.getPackageName())){
			return -1;
		}else if(!amsAppsubmitInfo.getPackageTypeId().equals(amsApp.getPackageTypeId())){
			return -2;
		}else if(!amsAppsubmitInfo.getAppName().equals(amsApp.getAmsAppname().getAppname())){
			return -3;
		}else if(Long.valueOf(amsAppsubmitInfo.getAppVersioncode()).longValue()<=Long.valueOf(amsApp.getAppVersioncode()).longValue()){
			return -4;
		}else if(amsAppsubmitInfo.getPrice().doubleValue()!=amsApp.getAppPrice().doubleValue()){
			return -5;
		}
		return 1;
	}
	public FormFile getFormFile(Map formFiles ,String fileKey){
		FormFile formFile=(FormFile)formFiles.get(fileKey);
		if(formFile==null){
			return null;
		}
		String name;
		try {
			name = new String(formFile.getFileName().getBytes(),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
		long size = formFile.getFileSize();
		//检查原来的没有变的化的图片
		if (name == null || name.equals("")|| size == 0) {
			return null;
		}					
		return formFile;
	}
	
	/**
	 * 取得文件列表
	 * fileKey=appimges
	 * @param formFiles
	 * @param fileKey
	 * @return
	 */
	public FormFile[] getFormFileArrary(Map formFiles ,String fileKey){
		Vector vector=new Vector();
		Iterator enumeration=formFiles.keySet().iterator();
		while(enumeration.hasNext()){
			String  keyname=(String)enumeration.next();
			FormFile formFile =(FormFile )formFiles.get(keyname);
			String name;
			try {
				name = new String(formFile.getFileName().getBytes(),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				continue;
			}
			long size = formFile.getFileSize();
			//检查原来的没有变的化的图片
			if ((name == null || name.equals("")) && size == 0) {
				continue;
			}			
			if(keyname.startsWith("appimges")){
				vector.add(formFile);
			}
		}
		return (FormFile[])vector.toArray(new FormFile[]{});
	}	
	public void setFromImg(AmsAppFrom amsAppFrom ,Set<AmsAppsubmitImage> imgSet){
		Iterator it = imgSet.iterator();
		List<AmsAppsubmitImage> list = new ArrayList<AmsAppsubmitImage>();
		amsAppFrom.setAmsAppimgs1(new java.util.LinkedHashSet());
		while (it.hasNext()) {
			AmsAppsubmitImage amsAppImg = (AmsAppsubmitImage) it.next();
			if(amsAppImg.getAvailable()==0){
				continue ;
			}
			AmsAppimg amsAppimg=getAmsAppimg(amsAppImg);
			if(amsAppImg.getImageType()==0){
				amsAppFrom.setAmsAppimgs0(amsAppimg);
			}
			if(amsAppImg.getImageType()==1){
				amsAppFrom.getAmsAppimgs1().add(amsAppimg);
			}
			if(amsAppImg.getImageType()==2){
				amsAppFrom.setAmsAppimgs2(amsAppimg);
			}
			if(amsAppImg.getImageType()==3){
				amsAppFrom.setAmsAppimgs3(amsAppimg);
			}
			if(amsAppImg.getImageType()==4){
				amsAppFrom.setAmsAppimgs4(amsAppimg);					
			}
			if(amsAppImg.getImageType()==5){
				amsAppFrom.setAmsAppimgs5(amsAppimg);							
			}
			if(amsAppImg.getImageType()==7){
				amsAppFrom.setAmsAppimgs7(amsAppimg);							
			}
			if(amsAppImg.getImageType()==6){
				amsAppFrom.setAmsAppimgs6(amsAppimg);							
			}
			
			if(amsAppImg.getImageType()==8){
				amsAppFrom.setAmsAppimgs8(amsAppimg);							
			}
			if(amsAppImg.getImageType()==9){
				amsAppFrom.setAmsAppimgs9(amsAppimg);							
			}
			if(amsAppImg.getImageType()==10){
				amsAppFrom.setAmsAppimgs10(amsAppimg);							
			}
		}
	}
	/**
	 * 如果2 3的图片可以检查是否重新上传
	 * @param mapping
	 * @param amsAppFrom
	 * @param request
	 * @param response
	 * @param amsAppsubmitInfo
	 * @return
	 */
	public Set updateFileImg(ActionMapping mapping, AmsAppFrom amsAppFrom,
			HttpServletRequest request, HttpServletResponse response,AmsAppsubmitInfo amsAppsubmitInfo) {

		List fileItems;
		Set imgVector=new java.util.LinkedHashSet();
		try {
			//下载文件
			String filePre=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
			String imgsIndexs=request.getParameter("imgsIndexPathArrary");
			String imgsIndexArrary[]=imgsIndexs.split(",");
			Vector imgsIndexPathArrary=new Vector();
			//快照图片按提交的顺序添加
			for(int i=0;imgsIndexArrary!=null&&i<imgsIndexArrary.length;i++){
				if(imgsIndexArrary[i]==null||imgsIndexArrary[i].trim().length()==0){
					continue;
				}
				String value[]=new String []{"1",imgsIndexArrary[i]};
				imgsIndexPathArrary.add(value);
			}
			
			imgsIndexs=request.getParameter("imgsIndexPath2");
			imgsIndexArrary=imgsIndexs.split(",");
			//快照图片按提交的顺序添加
			for(int i=0;imgsIndexArrary!=null&&i<imgsIndexArrary.length;i++){
				if(imgsIndexArrary[i]==null||imgsIndexArrary[i].trim().length()==0){
					continue;
				}
				String value[]=new String []{"2",imgsIndexArrary[i]};
				imgsIndexPathArrary.add(value);
				break;
			}			
			imgsIndexs=request.getParameter("imgsIndexPath3");
			imgsIndexArrary=imgsIndexs.split(",");
			//快照图片按提交的顺序添加
			for(int i=0;imgsIndexArrary!=null&&i<imgsIndexArrary.length;i++){
				if(imgsIndexArrary[i]==null||imgsIndexArrary[i].trim().length()==0){
					continue;
				}
				String value[]=new String []{"3",imgsIndexArrary[i]};
				amsAppsubmitInfo.setIconPath(value[1]);
				imgsIndexPathArrary.add(value);
				break;
			}

			//快照
			
			Set<AmsAppimg> amsAppimgs1 =amsAppFrom.getAmsAppimgs1(); 
			
			amsAppFrom.setAmsAppimgs1(new java.util.LinkedHashSet());
			for(int x=0;x<imgsIndexPathArrary.size();x++){   
				String  dateArrary[]=(String[])imgsIndexPathArrary.get(x);
				String  filePathx=(String)dateArrary[1];
				File file=new File(filePre+filePathx);
				String  saveurl =filePre+filePathx;
			    File filepath = new File(filePre,filePathx);
			    //
//			    if (!filepath.exists()){ 升级时，文件可能不在本地目录
//					//logger.debug(LanguageResourceFactory.getString("CLASS0048")+filepath.getCanonicalPath());
//			    	continue;
//			    }
			    AmsAppsubmitImage amsAppsubmitImage=new AmsAppsubmitImage();
			    Long imageType=Long.valueOf(dateArrary[0]);
			    amsAppsubmitImage.setImageType(imageType);//appimgsFile_0.getContentType());
				amsAppsubmitImage.setAvailable(1L);
				amsAppsubmitImage.setImagePath(filePathx);
				amsAppsubmitImage.setImageTime(new Date());
				//amsAppsubmitImage.setImageMime(formFile.getContentType());
				amsAppsubmitImage.setImageName(filepath.getName());
				imgVector.add(amsAppsubmitImage);
				AmsAppimg amsAppimg=new AmsAppimg();
				amsAppimg.setAppimgPath(amsAppsubmitImage.getImagePath());
				amsAppimg.setAvailable(amsAppsubmitImage.getAvailable());
				amsAppimg.setAppimgType(""+amsAppsubmitImage.getImageType());
				LLJTranUtil lLJTranUtil=new LLJTranUtil();
				if(amsAppsubmitImage.getImageType()==1){
					amsAppFrom.getAmsAppimgs1().add(amsAppimg);
					AmsAppimg amsAppimg_old=checkAmsAppimgIsExist(amsAppimg.getAppimgPath(),amsAppimgs1);
					if(amsAppimg_old==null){
						//新上传的文件
						
						//一定要存在
						if(lLJTranUtil.jpegRemoveThumbnail(amsAppsubmitImage)==-1){				
						}


						this.addBlob(amsAppsubmitImage);
					}else{
						amsAppsubmitImage.setImageId(amsAppimg_old.getAppimgId());
						amsAppimg.setAppimgId(amsAppimg_old.getAppimgId());
						amsAppimg.setImgSize(amsAppimg_old.getImgSize());
						amsAppsubmitImage.setImgSize(amsAppimg_old.getImgSize());
					}
					//检查文件是否新上传
				}else if(amsAppsubmitImage.getImageType()==2){
					AmsAppimg old_AmsAppimg=amsAppFrom.getAmsAppimgs2();
					if(old_AmsAppimg!=null){
						if(!old_AmsAppimg.getAppimgPath().equals(amsAppsubmitImage.getImagePath())){
							//说明新上传
							if(lLJTranUtil.jpegRemoveThumbnail(amsAppsubmitImage)==-1){				
							}
							this.addBlob(amsAppsubmitImage);
						}
						amsAppsubmitImage.setImageId(old_AmsAppimg.getAppimgId());
						amsAppsubmitImage.setImgSize(old_AmsAppimg.getImgSize());
						amsAppimg.setImgSize(old_AmsAppimg.getImgSize());
						
					}else{
						this.addBlob(amsAppsubmitImage);
					}
					
					amsAppFrom.setAmsAppimgs2(amsAppimg);
				}else if(amsAppsubmitImage.getImageType()==3){
					AmsAppimg old_AmsAppimg=amsAppFrom.getAmsAppimgs3();
					if(old_AmsAppimg!=null){
						if(!old_AmsAppimg.getAppimgPath().equals(amsAppsubmitImage.getImagePath())){
							//说明新上传
							if(lLJTranUtil.jpegRemoveThumbnail(amsAppsubmitImage)==-1){				
							}
							this.addBlob(amsAppsubmitImage);
						}
						amsAppsubmitImage.setImageId(old_AmsAppimg.getAppimgId());
						amsAppsubmitImage.setImgSize(old_AmsAppimg.getImgSize());
						amsAppimg.setImgSize(old_AmsAppimg.getImgSize());
					}else{
						this.addBlob(amsAppsubmitImage);
					}	
					amsAppFrom.setAmsAppimgs3(amsAppimg);
				}
				
			}
		
		}catch(Exception e){
			LogFactory.getLog(this.getClass()).error(LanguageResourceFactory.getString("CLASS0098")+e.getLocalizedMessage());
		}
		return imgVector;
	}
	
	/**
	 * 上传 类型 0 4 5
	 * 如果包类型0，则设 apkMap 
	 * 只是上传文件
	 * @param mapping
	 * @param amsAppFrom
	 * @param request
	 * @param response
	 * @param amsAppsubmitInfo
	 * @param keyName
	 * @param imgType
	 * @return 1 正常 -1 上传异常 0:上传包出错 -2:读取apk包出错 -6 上传apk包版本号为空  
	 * -7 上传apk包版本号数据格式不正确 -8 上传apk包包名为空 -9 上传apk包版本名称为空 -11 不同版本号　-12 不同包名 -13 不同名称
	 */
	public int  updateFile7(ActionMapping mapping, AmsAppFrom amsAppFrom,HttpServletRequest request, HttpServletResponse response,AmsAppsubmitInfo amsAppsubmitInfo) {
		try {
				String filePre=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
		        //下载开始
				MultipartRequestHandler mrh = amsAppFrom.getMultipartRequestHandler();
				Map formFiles = mrh.getFileElements();
				FormFile formFile=this.getFormFile(formFiles, "appimgs_7");
				AmsAppsubmitImage amsAppsubmitImage=null;
					if(formFile!=null){
						amsAppsubmitImage=updateFile(formFiles,"appimgs_7",7L);
						if(amsAppsubmitImage!=null){
							String newFile=filePre+"/"+amsAppsubmitImage.getImagePath();
							if(amsAppsubmitInfo.getPackageTypeId()!=1){
								//添加多线临时目录
								String tempNum="t"+System.currentTimeMillis();
								tempNum+=org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(8);
								Map map=this.getApkMap(newFile, "d:/temp2/"+tempNum);
								if(map!=null){
									amsAppFrom.setApkMap(map);
									int updateApkInfo=checkTryUpdateApkInfo(amsAppsubmitInfo,amsAppFrom.getApkMap());
									if(updateApkInfo==-1){
										return -6 ;
									}else if(updateApkInfo==-2){
										return -7 ;
									}else if(updateApkInfo==-3){
										return -8 ;
									}else if(updateApkInfo==-4){
										return -9 ;
									}else if(updateApkInfo==-11){
										return -11 ;
									}else if(updateApkInfo==-12){
										return -12 ;
									}else if(updateApkInfo==-13){
										return -13 ;
									}
									//检查检是否包是否相
								}else{
									return -2;
								}
							}
						}
					}
					if(formFile!=null&&amsAppsubmitImage==null){
						//上传出错
						return 0;
					}
				if(amsAppsubmitImage!=null){
					amsAppsubmitImage.setImageType(7L);
					amsAppsubmitImage.setAvailable(1L);
						amsAppsubmitInfo.getAmsAppsubmitImages().add(amsAppsubmitImage);
//						amsAppsubmitInfo.setAppPath(amsAppsubmitImage.getImagePath());
//						amsAppsubmitInfo.setAppSize(""+formFile.getFileSize());								
						amsAppFrom.setNewUploadAppimgs7(true);
						if(amsAppFrom.getAmsAppimgs7()!=null&&amsAppFrom.getAmsAppimgs7().getAppimgId()!=null){
							amsAppsubmitImage.setImageId(amsAppFrom.getAmsAppimgs7().getAppimgId());
						}	
					}
			
			//设置图片到form
		} catch (Exception e) {
			//logger.debug(LanguageResourceFactory.getString("CLASS0019"), e);
			LogFactory.getLog(this.getClass()).error(LanguageResourceFactory.getString("CLASS0099")+e.getLocalizedMessage());
			return -1;
		}
		return 1;
	}
	/**
	 * 上传 类型 0 4 5
	 * 如果包类型0，则设 apkMap 
	 * 只是上传文件
	 * @param mapping
	 * @param amsAppFrom
	 * @param request
	 * @param response
	 * @param amsAppsubmitInfo
	 * @param keyName
	 * @param imgType
	 * @return 1 正常 -1 上传异常 0:上传包出错 -2:读取apk包出错 -6 上传apk包版本号为空 
	 * -7 上传apk包版本号数据格式不正确 -8 上传apk包包名为空 -9 上传apk包版本名称为空 
	 */
	public int  updateFile0(ActionMapping mapping, AmsAppFrom amsAppFrom,HttpServletRequest request, HttpServletResponse response,AmsAppsubmitInfo amsAppsubmitInfo) {
		try {
				String filePre=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
		        //下载开始
				MultipartRequestHandler mrh = amsAppFrom.getMultipartRequestHandler();
				Map formFiles = mrh.getFileElements();
				FormFile formFile0=this.getFormFile(formFiles, "appimgs_0");
				AmsAppsubmitImage amsAppsubmitImage0=null;
					if(formFile0!=null){
						amsAppsubmitImage0=updateFile(formFiles,"appimgs_0",0L);
						if(amsAppsubmitImage0!=null){
							String newFile=filePre+"/"+amsAppsubmitImage0.getImagePath();
							if(amsAppsubmitInfo.getPackageTypeId()!=1){
								String tempNum="t"+System.currentTimeMillis();
								tempNum+=org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(8);
								Map map=this.getApkMap(newFile, "d:/temp2/"+tempNum);								
								if(map!=null){
									amsAppFrom.setApkMap(map);
									int updateApkInfo=updateApkInfo(amsAppsubmitInfo,amsAppFrom.getApkMap());
									if(updateApkInfo==-1){
										return -6 ;
									}else if(updateApkInfo==-2){
										return -7 ;
									}else if(updateApkInfo==-3){
										return -8 ;
									}else if(updateApkInfo==-4){
										return -9 ;
									}									
								}else{
									return -2;
								}
							}
						}
					}
					if(formFile0!=null&&amsAppsubmitImage0==null){
						//上传出错
						return 0;
					}
				if(amsAppsubmitImage0!=null){
						amsAppsubmitImage0.setImageType(0L);
						amsAppsubmitImage0.setAvailable(1L);
						amsAppsubmitInfo.getAmsAppsubmitImages().add(amsAppsubmitImage0);
//						amsAppsubmitInfo.setAppPath(amsAppsubmitImage0.getImagePath());
//						amsAppsubmitInfo.setAppSize(""+formFile0.getFileSize());								
						amsAppFrom.setNewUploadAppimgs0(true);
						if(amsAppFrom.getAmsAppimgs0()!=null&&amsAppFrom.getAmsAppimgs0().getAppimgId()!=null){
							amsAppsubmitImage0.setImageId(amsAppFrom.getAmsAppimgs0().getAppimgId());
						}	
					}
			
			//设置图片到form
		} catch (Exception e) {
			//logger.debug(LanguageResourceFactory.getString("CLASS0019"), e);
			LogFactory.getLog(this.getClass()).error(LanguageResourceFactory.getString("CLASS0099")+e.getLocalizedMessage());
			return -1;
		}
		return 1;
	}	
	/**
	 *  1 正常 -1 上传异常 0:上传包出错  -4 上传需求出错 -5 上传需求测试出错
	 * @param mapping
	 * @param amsAppFrom
	 * @param request
	 * @param response
	 * @param amsAppsubmitInfo
	 * @return
	 */
	public int  updateFile(ActionMapping mapping, AmsAppFrom amsAppFrom,HttpServletRequest request, HttpServletResponse response,AmsAppsubmitInfo amsAppsubmitInfo) {
		try {
					String filePre=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
			        //下载开始
					MultipartRequestHandler mrh = amsAppFrom.getMultipartRequestHandler();
					Map formFiles = mrh.getFileElements();
					FormFile  formFile4=this.getFormFile(formFiles, "appimgs_4");
					AmsAppsubmitImage amsAppsubmitImage4=null;
					if(formFile4!=null){
						amsAppsubmitImage4=updateFile(formFiles,"appimgs_4",4L);
					}
					if(formFile4!=null&&amsAppsubmitImage4==null){
						//上传出错
						return -4;
					}
					FormFile formFile5=this.getFormFile(formFiles, "appimgs_5");
					AmsAppsubmitImage amsAppsubmitImage5=null;
					if(formFile5!=null){
						amsAppsubmitImage5=updateFile(formFiles,"appimgs_5",5L);
					}
					if(formFile5!=null&&amsAppsubmitImage5==null){
						//上传出错
						return -5;
					}

					if(amsAppsubmitImage4!=null){
						amsAppsubmitImage4.setAvailable(1L);
						amsAppsubmitImage4.setImageType(4L);							
						amsAppFrom.setNewUploadAppimgs4(true);
						amsAppsubmitInfo.getAmsAppsubmitImages().add(amsAppsubmitImage4);
						if(amsAppFrom.getAmsAppimgs4()!=null&&amsAppFrom.getAmsAppimgs4().getAppimgId()!=null){
							amsAppsubmitImage4.setImageId(amsAppFrom.getAmsAppimgs4().getAppimgId());
						}
						//amsAppFrom.setAmsAppimgs4(getAmsAppimg(amsAppsubmitImage4));
					
					}						
					if(amsAppsubmitImage5!=null){
						amsAppsubmitImage5.setAvailable(1L);
						amsAppsubmitImage5.setImageType(5L);							
						amsAppFrom.setNewUploadAppimgs5(true);
						amsAppsubmitInfo.getAmsAppsubmitImages().add(amsAppsubmitImage5);
						if(amsAppFrom.getAmsAppimgs5()!=null&&amsAppFrom.getAmsAppimgs5().getAppimgId()!=null){
							amsAppsubmitImage5.setImageId(amsAppFrom.getAmsAppimgs5().getAppimgId());
						}
						//amsAppFrom.setAmsAppimgs5(getAmsAppimg(amsAppsubmitImage5));
					}					
			
			//设置图片到form
		} catch (Exception e) {
			//logger.debug(LanguageResourceFactory.getString("CLASS0019"), e);
			LogFactory.getLog(this.getClass()).error(LanguageResourceFactory.getString("CLASS0099")+e.getLocalizedMessage());
			return -1;
		}
		return 1;
	}
	



 /**
  * 上传信息转换lca需要的xml信息
  * @param amsAppsubmitInfo
  * @return
  */
  public static org.jdom.Document getLcaXml(AmsAppsubmitInfo amsAppsubmitInfo,boolean isTry){
		String platform = amsAppsubmitInfo.getDeviceSupport();
		String miniLcaSdkVersion = amsAppsubmitInfo.getSupportMinVersion();
		Long appid = 0l;
		if (null != amsAppsubmitInfo.getAppapkid() && !"".equals(amsAppsubmitInfo.getAppapkid())){
			appid = amsAppsubmitInfo.getAppapkid();
		} else {
			appid = amsAppsubmitInfo.getInfoId();//新建应用时没有
		}
		String version = amsAppsubmitInfo.getAppVersioncode();
		String name = amsAppsubmitInfo.getAppName();
		Long authcode = amsAppsubmitInfo.getAuthTypeId();
		Boolean widget = amsAppsubmitInfo.getIsWidget() == 1 ? true : false;
		Long pushAppType = amsAppsubmitInfo.getPushTypeId();
		Long cmtype = amsAppsubmitInfo.getPushContentsId();
		String sid = amsAppsubmitInfo.getPushId();
		boolean isPush = amsAppsubmitInfo.getPushEnable() == 1 ? true : false;

		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		xml.append("<lcainfo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
		xml.append("<platform><![CDATA[" + platform + "]]></platform>");
		xml.append("<mini-lca-sdk-version><![CDATA[" + miniLcaSdkVersion + "]]></mini-lca-sdk-version>");
		xml.append("<appid><![CDATA[" + appid + "]]></appid>");
		xml.append("<version><![CDATA[" + version + "]]></version>");
		xml.append("<name><![CDATA[" + name + "]]></name>");
		xml.append("<demoversion><![CDATA[" +isTry+ "]]></demoversion>");
		xml.append("<apptype><![CDATA[" + amsAppsubmitInfo.getTypeDeclare() + "]]></apptype>");
		
		xml.append("<authcode><![CDATA[" + authcode + "]]></authcode>");
		if (isPush) {
			xml.append("<push>");
			xml.append("<push-app-type><![CDATA[" + pushAppType + "]]></push-app-type>");
			if (pushAppType == 0) {
				xml.append("<cmtype><![CDATA[" + cmtype + "]]></cmtype>");
			}
			xml.append("<sid><![CDATA[" + sid + "]]></sid>");
			xml.append("</push>");
		}
		xml.append("<widget><![CDATA[" + widget + "]]></widget>");
		xml.append("</lcainfo>");
		//os.write(xml.toString().getBytes("UTF-8"));
		org.jdom.input.SAXBuilder SAXBuilder=new SAXBuilder();
		java.io.StringReader xmlReader=new StringReader(xml.toString());
		try {
//			org.jdom.output.XMLOutputter dd=new XMLOutputter();
//			dd.output(SAXBuilder.build(xmlReader), new JarOutputStream(System.out));
			return SAXBuilder.build(xmlReader);
			
		} catch (Exception e) {
			LogFactory.getLog(AppLogicBean.class).error("应用信息生成lcaXml文件出错:"+e.getLocalizedMessage());
		}
		return null;

  }
	/**
	 * 图片类型(1：快照，2：宣传图,0:jar,3:图标,4：需求,5：测试,6：正式lca包 ,7:试用版应用包 ,8:试用版本lca包,9:正式版本jar类型jad文件 10:试用版本jar类型jad文件)
	 */
  	/**
  	 * 
  	 * @param amsAppFrom
  	 * @param amsAppsubmitInfo
  	 * @param isTry true:试用 false 正式
  	 * @return 1 成功 -1 主包不存在 -2 jad不存在 -3 生成xml文件出错  -4 lca临时文件不存在 -5 签名出错 -6 没有初始化联想认证文件 -7 不是联想公钥
  	 * @throws LmmException 
  	 * @throws IOException 
  	 * @throws SQLException 
  	 */
	public static synchronized int  autoJar(AmsAppFrom amsAppFrom,AmsAppsubmitInfo amsAppsubmitInfo,boolean isTry,Long oldLong) {
		String filePre=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
	    String filePath_jar=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_JAR);
	    List tempListImg=new Vector();
	    Long file_one=0L;
	    Long file_two=9L;
	    if(isTry){
	    	file_one=7L;
	    	file_two=10L;
	    }
        boolean isOldBlob=false;
        boolean isOldBlobJad=false;
    	File lca_tempFile=null;
    	String reg="(\\.{1}[^\\.]*?$)";//最后的扩展名
        try{
	    	 List<AmsAppsubmitImage> tempList=getAmsAppsubmitImage(amsAppsubmitInfo.getAmsAppsubmitImages(),file_one );
	    	 AmsAppsubmitImage amsAppsubmitImageApkJar=null;
	    	 AmsAppsubmitImage amsAppsubmitImageJad=null;
	    	 if(tempList.size()>0){
	    		 amsAppsubmitImageApkJar=tempList.get(0);
	    		 AmsAppsubmitImage amsAppsubmitImageLca=new AmsAppsubmitImage();
	    		 if(amsAppsubmitImageApkJar.getImagePic()==null){
	    			 //从数据库读取
	    				com.lenovo.lmm.appman.logic.delegate.AppDelegate  appDelegate=new AppDelegate();
	    				java.sql.Blob blob= appDelegate.getAppimgByAppimgPath(amsAppsubmitImageApkJar.getImagePath(), true);
	    				if(blob!=null){
	    					amsAppsubmitImageApkJar.setImagePic(blob);
	    					isOldBlob=true;
	    				}else{
	    					//出错
	    					return -1;
	    				}
	    		 }
	    	 }else{
	    		 //出错
	    		 return -1;
	    	 }
	    	 //20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
	    	 /***********************#####20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
	 		if(amsAppsubmitInfo.getPackageTypeId()==1){
		    	 tempList=getAmsAppsubmitImage(amsAppsubmitInfo.getAmsAppsubmitImages(),file_two );
		    	 if(tempList.size()>0){
		    		 amsAppsubmitImageJad=tempList.get(0);
		    		 if(amsAppsubmitImageJad.getImagePic()==null){
		    			 //从数据库读取
		    				com.lenovo.lmm.appman.logic.delegate.AppDelegate  appDelegate=new AppDelegate();
		    				java.sql.Blob blob= appDelegate.getAppimgByAppimgPath(amsAppsubmitImageJad.getImagePath(), true);
		    				if(blob!=null){
		    					amsAppsubmitImageJad.setImagePic(blob);
		    					isOldBlobJad=true;
		    				}else{
		    					//数据库没有文件
		    					return -2;
		    				}
		    		 }
		    	 }else{
		    		 //出错
		    		 return -2;
		    	 }
	 		}
    	 
    	 #####20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
    	 *
    	 ***************************/
	    	String jarfilePre= filePre+("/"+amsAppsubmitImageApkJar.getImagePath());
	    	jarfilePre=jarfilePre.replaceAll("/+","/");
	    	File jarFile_temp=new File(jarfilePre);//改名

	    	lca_tempFile=new File(jarFile_temp.getParentFile(),jarFile_temp.getName().replaceAll(reg, ".lca_temp"));
	 		java.io.FileOutputStream fileOutputStream=new FileOutputStream(lca_tempFile);
	 		JarOutputStream out = new JarOutputStream(fileOutputStream);
	        InputStream in = amsAppsubmitImageApkJar.getImagePic().getBinaryStream();
	        addJarEntry(out ,in,jarFile_temp.getName());
	        in.close();
	        if(isOldBlob){
	        	amsAppsubmitImageApkJar.setImagePic(null);
	        }	   
	        /***********************#####20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
	 		if(amsAppsubmitInfo.getPackageTypeId()==1){
		 		jarfilePre= filePre+("/"+amsAppsubmitImageJad.getImagePath());
		 		jarfilePre=jarfilePre.replaceAll("/+","/");
		    	jarFile_temp=new File(jarfilePre);//改名
		        in=amsAppsubmitImageJad.getImagePic().getBinaryStream();
		        
		        ////////20100318添加更新jad的文件部分信息
		        String jadTxt="";
		        boolean isFristLine=true;
		        boolean isHaveMIDlet_Jar_Size=false;
		        boolean isHaveMIDlet_Jar_URL=false;
//		        in=amsAppsubmitImageJad.getImagePic().getBinaryStream();
		        java.io.BufferedReader  reader=new BufferedReader(new java.io.InputStreamReader(in,"UTF-8"));
		        while(true){
		        	String info=reader.readLine();
			        	if(info==null){
			        		if(!isHaveMIDlet_Jar_Size){
			        			info="MIDlet-Jar-Size: "+amsAppsubmitImageApkJar.getImgSize().longValue();
			        		}
			        		if(!isHaveMIDlet_Jar_URL){
			        			 info="MIDlet-Jar-URL: "+amsAppsubmitImageApkJar.getImageName();
			        		}
			        		break;
			        	}
			         if(info.matches("^MIDlet-Jar-Size:.*$")){
			        	 info="MIDlet-Jar-Size: "+amsAppsubmitImageApkJar.getImgSize().longValue();
			        	 isHaveMIDlet_Jar_Size=true;
			         }else if(info.matches("^MIDlet-Jar-URL:.*$")){
			        	 info="MIDlet-Jar-URL: "+amsAppsubmitImageApkJar.getImageName();
			        	 isHaveMIDlet_Jar_URL=true;
			         }
			        if(isFristLine){
			        	jadTxt+=info;        	
			        	isFristLine=false;
			        }else{
			        	jadTxt+="\n"+info;		
			        }


		        }	
		        in= new java.io.ByteArrayInputStream(jadTxt.getBytes());
		        /////////
		        
		        addJarEntry(out ,in,jarFile_temp.getName());
		        in.close();
		        if(isOldBlobJad){
		        	amsAppsubmitImageJad.setImagePic(null);
		        }
	 		}
	 		
	 		
    	 #####20100426 徐祥说暂时不用上传jad文件 何时改回来，不确定
    	 *
    	 ***************************/	 		
	 		try{
	 		//写入xml流
	 		//if(amsAppsubmitInfo.getPackageTypeId()==1){
		 		//jad java包上传jad
	 			Document doc=getLcaXml(amsAppsubmitInfo,isTry);
	 			String docXml=getDocString(doc);
		        in=new java.io.ByteArrayInputStream(docXml.getBytes());
		        addJarEntry(out ,in,"Lcainfo.xml");
		        in.close();
	 		//}	 		
	 		}catch(Exception e){
	 			return -3;
	 		}
	        out.close();
	        
	    	com.lenovo.lmm.appman.logic.delegate.AppDelegate  appDelegate=new AppDelegate();
			AmsAppSysInfo amsAppSysInfo_path = (AmsAppSysInfo)appDelegate.getAppSysInfoDelegate().getAmsAppSysInfo("SYS_KEYSTORE_FILE_PATH").get(0);
			AmsAppSysInfo SYS_KEYSTORE_STORE_PASSWD_amsAppSysInfo = (AmsAppSysInfo)appDelegate.getAppSysInfoDelegate().getAmsAppSysInfo("SYS_KEYSTORE_STORE_PASSWD").get(0);
			AmsAppSysInfo SYS_KEYSTORE_KEY_PASSWD_amsAppSysInfo = (AmsAppSysInfo)appDelegate.getAppSysInfoDelegate().getAmsAppSysInfo("SYS_KEYSTORE_KEY_PASSWD").get(0);
			AmsAppSysInfo SYS_KEYSTORE_KEY_ALIAS_amsAppSysInfo = (AmsAppSysInfo)appDelegate.getAppSysInfoDelegate().getAmsAppSysInfo("SYS_KEYSTORE_KEY_ALIAS").get(0);
			String SYS_KEYSTORE_STORE_PASSWD=SYS_KEYSTORE_STORE_PASSWD_amsAppSysInfo.getTextValue();
			
			String SYS_KEYSTORE_KEY_PASSWD=SYS_KEYSTORE_KEY_PASSWD_amsAppSysInfo.getTextValue();
			String SYS_KEYSTORE_KEY_ALIAS=SYS_KEYSTORE_KEY_ALIAS_amsAppSysInfo.getTextValue();
			com.lenovo.lps.appstore.security.AesCrypto aesCrypto=new AesCrypto();
			SYS_KEYSTORE_STORE_PASSWD=aesCrypto.decrypt(SYS_KEYSTORE_STORE_PASSWD);
			SYS_KEYSTORE_KEY_PASSWD=aesCrypto.decrypt(SYS_KEYSTORE_KEY_PASSWD);
			String keyFilePath=amsAppSysInfo_path.getTextValue();
            keyFilePath=keyFilePath.replaceAll("\\+", "/");
	        int isExistFile=checkKeystoreIsExist(appDelegate, SYS_KEYSTORE_STORE_PASSWD,SYS_KEYSTORE_KEY_PASSWD, SYS_KEYSTORE_KEY_ALIAS );
	        if(isExistFile!=1){
	        	//没有初始化联想认证文件或过期
	        	if(isExistFile==-3){
	             	LogFactory.getLog(AppLogicBean.class).error(LanguageResourceFactory.getString("CLASS00100"));	        		
	        		return -7;//
	        	}
	        	LogFactory.getLog(AppLogicBean.class).error(LanguageResourceFactory.getString("CLASS00101"));	   
	        	return -6;
	        }
	        
	      //记名
	        //jarsigner  -storepass lenovo -keystore D:\application\Jdk\jdk1.6.0_06\bin\.keystore   xxxxx.jar trialkey
	        //检查 keystore 一定要 -debug
	       // keytool -list -v  -debug -keystore D:\application\Jdk\jdk1.6.0_06\bin\.keystore -alias trialkey -storepass lenovo	       
	        
	        //String  arg="-list -v  -debug -keystore "+keyFilePath+" -alias trialkey -storepass lenovo";
	        
	        String  arg="-list -v  -debug  -keystore "+keyFilePath+" -alias "+SYS_KEYSTORE_KEY_ALIAS+" -keypass "+SYS_KEYSTORE_KEY_PASSWD+" -storepass "+SYS_KEYSTORE_STORE_PASSWD+"";
	        try{
	        	sun.security.tools.KeyTool.main(arg.split("\\s+"));
	        }catch(Exception e){   
	        	LogFactory.getLog(AppLogicBean.class).error(LanguageResourceFactory.getString("CLASS00102")+e.getLocalizedMessage());
	        	return -7;
	        }
	        if(lca_tempFile.exists()){
	        	try{
		        	arg="-storepass "+SYS_KEYSTORE_STORE_PASSWD+"  -keypass "+SYS_KEYSTORE_KEY_PASSWD+" -keystore "+keyFilePath+"  "+lca_tempFile.getAbsolutePath()+" "+SYS_KEYSTORE_KEY_ALIAS;
		 			String []args=arg.split("\\s+");
		 			sun.security.tools.JarSigner.main(args);
		 			String newName=lca_tempFile.getName().replaceAll("_temp$", "");
		 			File newLcaFile=new File(lca_tempFile.getParentFile(),newName);
		 			if(newLcaFile.exists()){
		 				newLcaFile.delete();
		 			}
		 			File oldFile=new File(newLcaFile.getParentFile(),"old"+newLcaFile.getName());
		 			if(newLcaFile.exists()){
		 				newLcaFile.renameTo(oldFile);
		 			}
		 			if(!lca_tempFile.renameTo(newLcaFile)){
		 				oldFile.renameTo(newLcaFile);
		 			}else{
		 				if(oldFile.exists()){
		 					oldFile.delete();
			 			}
		 			}
	        	}catch(Exception e){
		        	LogFactory.getLog(AppLogicBean.class).info(LanguageResourceFactory.getString("CLASS00103"),e);
	        		return  -5;
	        	}
	        }else{
	        	//lca包不存在
	        	LogFactory.getLog(AppLogicBean.class).info(LanguageResourceFactory.getString("CLASS00104")+lca_tempFile.getAbsolutePath());
	        	return -4;
	        }
			AmsAppsubmitImage amsAppsubmitImage=new AmsAppsubmitImage();
			amsAppsubmitImage.setAvailable(1L);
			
			String newFileStr=amsAppsubmitImageApkJar.getImagePath().replaceAll(reg, ".lca");
			File lcaFile=new File(newFileStr);
			amsAppsubmitImage.setImagePath(newFileStr);
			amsAppsubmitImage.setImageTime(new Date());
			amsAppsubmitImage.setImageName(lcaFile.getName());
			if(oldLong!=null){
				amsAppsubmitImage.setImageId(oldLong);
			}
			addBlob(amsAppsubmitImage);
	        if(!isTry){
	    		amsAppsubmitImage.setImageType(6L);//appimgsFile_0.getContentType());

	        }else{
	        	amsAppsubmitImage.setImageType(8L);//appimgsFile_0.getContentType());
	        }
	        amsAppsubmitInfo.getAmsAppsubmitImages().add(amsAppsubmitImage);
	        return 1;// 成功
        }catch(Exception e){
			LogFactory.getLog(AppLogicBean.class).error(LanguageResourceFactory.getString("CLASS00105")+e.getLocalizedMessage());
			if(lca_tempFile!=null&&lca_tempFile.exists()&&lca_tempFile.isFile()){
				lca_tempFile.delete();
			}
        }

	    return -1;
	}
	
	

	/**
	 * jar 新的jar添加文件
	 * @param out
	 * @param in
	 * @param fileName
	 * @return 1 成功 -1 失败
	 */
	public static int addJarEntry(JarOutputStream out ,InputStream in,String fileName){
 		//jad java包上传jad
		JarEntry e = new JarEntry(fileName);
        try {
			out.putNextEntry(e);
	 		int bytesRead = 0;
	 		byte []buffer =null;
	
	 		buffer = new byte[in.available()];
	 		while ((bytesRead = in.read(buffer))>0) {
	 			out.write(buffer,0,bytesRead); 			
	 			
	 		}
	 		out.flush();		
	 		out.closeEntry();		
	 		return 1;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return -1;
	}	
	/**
	 * Document 生成的xml字符串
	 * @param doc
	 * @return
	 */
	public static String getDocString(Document doc){
		org.jdom.output.XMLOutputter xmlOut=new XMLOutputter();
		try {
			return xmlOut.outputString(doc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 检查是存在联想认证文件
	 * 如果没有则成数据库取认证文件
	 * @return 1 存在 -1 异常　-2　数库没有初始化联想认认文件 -3 密钥过期
	 */
	public static synchronized int checkKeystoreIsExist( AppDelegate appDelegate,final String SYS_KEYSTORE_STORE_PASSWD,final String SYS_KEYSTORE_KEY_PASSWD, final String SYS_KEYSTORE_KEY_ALIAS){
		String SYS_KEYSTORE_BLOB="SYS_KEYSTORE_BLOB";
		String SYS_KEYSTORE_FILE_PATH="SYS_KEYSTORE_FILE_PATH";
		List<AmsAppSysInfo> list;
		try {

			
			AmsAppSysInfo amsAppSysInfo_path = (AmsAppSysInfo)appDelegate.getAppSysInfoDelegate().getAmsAppSysInfo(SYS_KEYSTORE_FILE_PATH).get(0);
            String keyFilePath=amsAppSysInfo_path.getTextValue();
			File keyFilePathFile=new File(keyFilePath);
			if(!keyFilePathFile.exists()){//||!keyFilePathFile.isFile()
				list = appDelegate.getAppSysInfoDelegate().getAmsAppSysInfo(SYS_KEYSTORE_BLOB);
				if(list!=null&&list.size()>0){
					AmsAppSysInfo amsAppSysInfo=list.get(0);
					
					if(amsAppSysInfo.getBlobValue()==null||amsAppSysInfo.getBlobValue().length()==0){
		             	LogFactory.getLog(AppLogicBean.class).info(LanguageResourceFactory.getString("CLASS00106"));	      						
						return -1;
					}else{  
					 	java.io.InputStream in=amsAppSysInfo.getBlobValue().getBinaryStream();
						long length=FileUtil.saveFileStream(in, keyFilePathFile.getName(), keyFilePathFile.getParentFile().getCanonicalPath().replaceAll("\\+", "/"));
						if(length==0){
			             	LogFactory.getLog(AppLogicBean.class).info(LanguageResourceFactory.getString("CLASS00107"));	      							
							return -2;
						}
	
					}
				}
				boolean isOk=checkValidity(new File(keyFilePath) ,SYS_KEYSTORE_KEY_ALIAS,SYS_KEYSTORE_STORE_PASSWD);//"lenovo"
				if(!isOk){
					return -3;// 密钥过期
				}
			}else{
				boolean isOk=checkValidity(keyFilePathFile ,SYS_KEYSTORE_KEY_ALIAS,SYS_KEYSTORE_STORE_PASSWD);
				if(!isOk){
					keyFilePathFile.delete();
					checkKeystoreIsExist(appDelegate,SYS_KEYSTORE_STORE_PASSWD,SYS_KEYSTORE_KEY_PASSWD, SYS_KEYSTORE_KEY_ALIAS );
				}
			}
			return 1;

		} catch (Exception e) {
			LogFactory.getLog(AppLogicBean.class).info(LanguageResourceFactory.getString("CLASS00108"),e);
			return -1;
		}
		
		
		

	}

	/**
	 * 
	 * @param fis
	 * @param alias 
	 * @param password 密码：keystore password
	 * @return
	 */
	public static boolean checkValidity(InputStream fis ,String alias,String password){
	     try {
		       KeyStore ks = KeyStore.getInstance("JKS");
		       ks.load(fis, password.toCharArray());
		       java.security.cert.Certificate certificate=ks.getCertificate(alias);
	           X509Certificate certificate509=(X509Certificate)certificate;
		       X509Certificate c=certificate509;
		       c.checkValidity(new Date(System.currentTimeMillis()-2000*20));
		     }
		     catch (Exception ex) {
					LogFactory.getLog(AppLogicBean.class).error("检查联想密钥有效期失败",ex);
		    	 return false;
		     }
		     return true;
	}

	/**
	 * CheckSigner verify =   new CheckSigner(); 
	    返回码含义如下，其中： 
	    "00000" 校验签名成功; 
	    "11111" 校验apk签名错误或异常; 
	    "00001" 使用Android Debug签名apk包 ; 
	    "00002" 签名有效期小于25年 ;
	    "xxxxx" 文件不存在	
	    
	 * @param amsAppsubmitImage
	 * @return 
	 */
	public String verify(AmsAppsubmitImage amsAppsubmitImage){
		
		/**20100721 1 添加检查apk是否与原版签名是否致
					2 添加检查apk包是否有效及是否debug标识
    	CheckSigner verify =   new CheckSigner(); 
	    String resultCode verify. verify (args[0],30); 
	    返回码含义如下，其中： 
	    "00000" 校验签名成功; 
	    "11111" 校验apk签名错误或异常; 
	    "00001" 使用Android Debug签名apk包 ; 
	    "00002" 签名有效期小于25年 							
		**/
		if(amsAppsubmitImage!=null){
			java.sql.Blob blob=amsAppsubmitImage.getImagePic();
			if(blob!=null){
				String filePrex=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
				File filePreFile=new File(filePrex+amsAppsubmitImage.getImagePath());
				if(filePreFile.exists()){
					CheckSigner verify =   new CheckSigner(); 
					return verify.verify(filePreFile.getAbsolutePath().replaceAll("\\\\+", "/"), 30);//
				}
				
			}
		}
		return "xxxx";
	}
	/**
	 * 检查两个apk包是否一样的签名
	 * @see CheckJarsigner#equalsSamePubKey
	 * @param amsAppsubmitImageNew
	 * @param amsAppsubmitImageOld
	 * @return 1 找到相同的公钥; 0不存在相同的公钥; -1 新文件没有签名 ; -2 新文件不存在签名文件.sf ; -3 旧文件不存在签名文件.sf
	 * @throws Exception 
	 */
	public String verifySameSigner(AmsAppsubmitImage amsAppsubmitImageNew,AmsAppsubmitImage amsAppsubmitImageOld) throws Exception{
			List<CodeSigner> listNews= new Vector();
			String filePrex=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
			File fileNewFile=new File(filePrex+amsAppsubmitImageNew.getImagePath());
			List<CodeSigner> listOlds= new Vector();
			filePrex=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
			File fileOldFile=new File(filePrex+amsAppsubmitImageOld.getImagePath());
			CheckJarsigner.getCodeSigners(fileNewFile, listNews);
			CheckJarsigner.getCodeSigners(fileOldFile, listOlds);
			return ""+CheckJarsigner.equalsSamePubKey(listNews, listOlds);
	}
	
	/**
	 * 从apk中读取manifest
	 * @param amsAppsubmitImage 
	 * @param amsAppsubmitInfo 应用信息
	 * @param isTry 是否试用版
	 * @return 10001:apk不存在 10002:apk中不包含AndroidManifest.xml文件 10003:读取文件异常
	 * @throws Exception 
	 */
	public void readAndroidManifest(AmsAppsubmitImage amsAppsubmitImage , AmsAppsubmitInfo amsAppsubmitInfo , boolean isTry) throws Exception{
		String androidManifest = "";
		if(amsAppsubmitImage!=null){
			java.sql.Blob blob=amsAppsubmitImage.getImagePic();
			if(blob!=null){
				String filePrex=AppProperties.getValue(AppProperties.AMS_APP_UPLOAD_ROOTPATH);
				File filePreFile=new File(filePrex+amsAppsubmitImage.getImagePath());
				if(filePreFile.exists()){
					androidManifest = ApkUtil.readAndroidManifestFromApk(filePreFile);
				}
				
			}
		}
		if("".equals(androidManifest)){
			throw new Exception("未找到apk包，请确认已经上传apk包");
		}
		else if("10002".equals(androidManifest)){
			throw new Exception("apk中不包含AndroidManifest.xml文件，请上传正确的apk");
		}
		else if("10003".equals(androidManifest) || null == androidManifest){
			throw new Exception("读取AndroidManifest.xml文件异常");
		}
		
	   AmsAppsubmitManifest appsubmitManifest = new AmsAppsubmitManifest();
	   if(isTry){
				appsubmitManifest.setFestType("1");//试用版
	   }
	   else{
			appsubmitManifest.setFestType("0");//正式版
	   }
	   appsubmitManifest.setMainFestString(androidManifest);
	   amsAppsubmitInfo.getAmsAppsubmitManifests().add(appsubmitManifest);
	 }

}
